<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 订单管理
 * @author Administrator
 *
 */
class Statistics extends MY_Controller {

	/**
	 * @var DlnUserModel
	 */
	public  $mMember = null;
	
	/**
	 * @var DlnOrderModel
	 */
	public  $mOrder = null;
	
	public function __construct(){
		parent::__construct();	
		$this->loadModel('DlnUserModel', 'mMember', 'deliveryman');
		$this->loadModel('DlnOrderModel', 'mOrder', 'deliveryman');
	}
	
	/**
	 * 首页
	 */
	public function index(){

		$this->loadModel('AdmSettingModel', 'mSetting', 'admin');
		$data = [
				'status' => $this->mOrder->status(),
				'type' => $this->mOrder->type(),
				'apconfig' => $this->mOrder->apConfig(),
				'province' => $this->mSetting->getProvinces()
		];
		$this->view('deliveryman/statistics/home', $data,'datatable,datepicker,select2');
	}

	/**
     * 列表
     */
	public function getList(){
        $this->loadModel('ConsumerOrderModel', 'mConOrder', 'consumer');

		$dateFrom = get('star');
		$dateTo = get('end');

		$deliveryman = trim(get('deliveryman'));
		$deliverymanMobile = trim(get('deliveryman_mobile'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"


		if($deliveryman){
			$this->db->like('u.name', $deliveryman);
		}
			
		if($deliverymanMobile){
			$this->db->where('u.mobile', $deliverymanMobile);
		}

        if ($iSortCol_0 == 2){
            $this->db->order_by('income', $sSortDir_0);
        }else if($iSortCol_0 == 3){
            $this->db->order_by('distance', $sSortDir_0);
        }else if($iSortCol_0 == 4){
            $this->db->order_by('shipping', $sSortDir_0);
        }else if($iSortCol_0 == 5){
            $this->db->order_by('accept', $sSortDir_0);
        }else if($iSortCol_0 == 6){
            $this->db->order_by('done', $sSortDir_0);
        }else if($iSortCol_0 == 7){
            $this->db->order_by('overtime', $sSortDir_0);
        }else{
            $this->db->order_by('ro.deliveryman_id desc');
        }

        //获取配送员运单完成情况
        $this->db->select('ro.deliveryman_id,u.name,u.mobile,
                            count(if(o.status in(2,3), o.id,null)) as shipping,
                            count(if(o.status in(2,3,4),o.id,null)) as accept,
                            count(if(o.status in(4),o.id,null)) as done,
                            count(if(o.status = 4 and co.expect_arrive_time < o.complete_time,o.id,null)) as overtime,
                            sum(if(o.status in(4), o.distance, null)) as distance,
                            sum(if(o.status in(4), o.income, null)) as income')
                ->join($this->mMember->tbUser.' u', 'u.id = ro.deliveryman_id')
                ->join($this->mOrder->tbOrder. ' o', 'o.id = ro.order_id')
                ->join($this->mConOrder->tbOrder.' co', 'o.order_id = co.id')
                ->where('ro.addtime >=', strtotime($dateFrom))
                ->where('ro.addtime <', strtotime('+1day', strtotime($dateTo)))
                ->group_by('ro.deliveryman_id');

        $data = $this->mOrder->pagination($this->mOrder->tbRelationOrder.' ro');

        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = $v['income']?$v['income']:0;
            $data['aaData'][$k][] =  $v['distance']?$v['distance']/1000:0;
            $data['aaData'][$k][] =  $v['shipping']?$v['shipping']:0;
            $data['aaData'][$k][] =  $v['accept']?$v['accept']:0;
            $data['aaData'][$k][] =  $v['done']?$v['done']:0;
            $data['aaData'][$k][] =  $v['overtime']?$v['overtime']:0;;

            $btnConfig = array(
            		array(
            				'label' => '详情',
            				'icon' => '<i class="fa fa-eye"></i>',
            				'attr' => array(
            						'href' => getUrl('deliveryman/statistics/details?id='.$v['deliveryman_id'].'&start='.$dateFrom.'&end='.$dateTo),
            						'class' => 'btn btn-xs btn-default',
            				),
            				'tag' => 'a'
            		),
            );
            
            $data['aaData'][$k][] = adminCreateBtn($btnConfig);
        }
        unset($data['data']);
        echo json_encode($data);
    }
    
    /**
     * 详情
     */
    public function details(){

    	$id = get('id');	
    	if( ! $id){
    		show_404();
    	}

        $info = $this->mMember->getInfo ( $id );
    	if( ! $info){
    		show_404();
    	}


    	$this->view('deliveryman/statistics/detail', $info,'datatable,datepicker,select2');
    }

    public function orderList(){
        $this->loadModel('ConsumerOrderModel', 'mConOrder', 'consumer');
        $id = (int)get('id');
        $dateFrom = get('start');
        $dateTo = get('end');

        $this->db->select('o.id,o.code,o.send_user,o.send_address, o.send_mobile,
				o.province_id,o.city_id,o.county_id,u.province_id as u_province_id,u.city_id as u_city_id,
				u.county_id as u_county_id,
				o.distance,o.send_to_mobile,o.status,o.addtime,co.expect_arrive_time,o.rob_expect_time,u.name,
				u.mobile,o.type,o.income,o.complete_time,ap.type as ap_type,ap.content as ap_content')
            ->join($this->mOrder->tbOrder.' o', 'ro.order_id = o.id')
            ->join($this->mMember->tbUser.' u', 'u.id = ro.deliveryman_id')
            ->join($this->mOrder->tbOrderAp.' ap', 'ap.order_id = o.id', 'left')
            ->join($this->mConOrder->tbOrder.' co', 'o.order_id = co.id')
            ->where('ro.deliveryman_id', $id)
            ->order_by('o.id desc');

        if($dateFrom){
            $this->db->where('ro.addtime >=', strtotime($dateFrom));
        }

        if($dateTo){
            $this->db->where('ro.addtime <', strtotime('+1day', strtotime($dateTo)));
        }
        $data = $this->mOrder->pagination($this->mOrder->tbRelationOrder.' ro');

        $addressId = [];
        foreach ($data['data'] as $v){
            if( ! in_array($v['province_id'], $addressId)){
                $addressId[] = $v['province_id'];
            }
            if( ! in_array($v['city_id'], $addressId)){
                $addressId[] = $v['city_id'];
            }
            if( ! in_array($v['county_id'], $addressId)){
                $addressId[] = $v['county_id'];
            }
            if( ! in_array($v['u_province_id'], $addressId)){
                $addressId[] = $v['u_province_id'];
            }
            if( ! in_array($v['u_city_id'], $addressId)){
                $addressId[] = $v['u_city_id'];
            }
            if( ! in_array($v['u_county_id'], $addressId)){
                $addressId[] = $v['u_county_id'];
            }
        }

        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $address = $this->mSett->getLocationNameByIds($addressId);
        foreach ($data['data'] as $k => $v){

            if($v['distance'] > 1000){
                $v['distance'] = ($v['distance'] / 1000).'km';
            }else{
                $v['distance'] = $v['distance'].'m';
            }

            $data['aaData'][$k][] = dateFormat($v['addtime'], true);
            $data['aaData'][$k][] = $v['code'];

            $tS = '';
            if($v['status'] == 1){
                $tS = isset($address[$v['province_id']]) ? $address[$v['province_id']]['name'] : '';
                $tSs = isset($address[$v['city_id']]) ? $address[$v['city_id']]['name'] : '';
                $tS .= $tSs == $tS ? '' : $tSs;
                $tS .= isset($address[$v['county_id']]) ? $address[$v['county_id']]['name'] : '';
            }else{
                $tS = isset($address[$v['u_province_id']]) ? $address[$v['u_province_id']]['name'] : '';
                $tSs = isset($address[$v['u_city_id']]) ? $address[$v['u_city_id']]['name'] : '';
                $tS .= $tSs == $tS ? '' : $tSs;
                $tS .= isset($address[$v['u_county_id']]) ? $address[$v['u_county_id']]['name'] : '';
            }

            $data['aaData'][$k][] = $tS;
            $data['aaData'][$k][] = $v['mobile'] ? $v['name'].'<br/><span style="color:grey;">（'.$v['mobile'].'）</span>' : '';
            $data['aaData'][$k][] = $v['distance'];
            $data['aaData'][$k][] = $v['income'];
            $data['aaData'][$k][] = $this->mOrder->type($v['type']);
            $tI = ceil((($v['status'] == 4 ? $v['complete_time'] : time()) -
                    ($v['status'] == 1 ? $v['rob_expect_time'] : $v['expect_arrive_time'])) / 60);
            $show  = '';
            if(abs($tI) < 60){
                $show = abs($tI).'分钟';
            }elseif(abs($tI) > 60){
                $e = abs($tI) % 60;
                $show = floor(abs($tI) / 60).'小时';
                if($e > 0){
                    $show .= $e.'分钟';
                }
            }

            if($tI > 0){
                if($v['status'] == 4){
                    $show = '超时'.$show;
                }else{
                    $show = '已超时'.$show;
                }
            }else{
                if($v['status'] == 4){
                    $show = '提前'.$show.'送达';
                }else{
                    $show = $show.'后超时';
                }
            }

            $data['aaData'][$k][] = $v['status'] != 5 ? $show : '';
            $data['aaData'][$k][] = $v['ap_type'] > 0 ? $this->mOrder->apConfig($v['ap_type'])
                .'<br/><a class="ap-content-btn" href="javascript:void(0);"><span class="type">查看备注</span>
            		<span class="content hide">'.nl2br($v['ap_content']).'</span></a>' : '未报备';
            $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
            $btnConfig = array(
                array(
                    'label' => '详情',
                    'icon' => '<i class="fa fa-eye"></i>',
                    'attr' => array(
                        'href' => getUrl('deliveryman/order/details?id='.$v['id']),
                        'class' => 'btn btn-xs btn-default',
                    ),
                    'tag' => 'a'
                ),
            );

            $data['aaData'][$k][] = adminCreateBtn($btnConfig);
        }
        unset($data['data']);
        echo json_encode($data);
    }
}
